from logging import fatal

from selenium import webdriver
from selenium.webdriver.common.by import By
import datetime
import pyautogui
import time
buy_time = '2024-11-24 08:00:00'#放票时间
# 购票参数
start_address = "北京西"
end_address = "西安北"
start_time = '2024-12-08'
# driver = webdriver.Edge()
driver = webdriver.Chrome()
# driver = webdriver.Firefox()
driver.maximize_window()

#进入京东首页
driver.get("https://www.12306.cn/index/")
# 点击登录按钮
driver.find_element(By.ID,"J-btn-login").click()
#登陆方法1
#输入账号密码
# uName = driver.find_element(By.ID,"J-userName")
# uName.send_keys("17691230520")
# uPassword = driver.find_element(By.ID,"J-password")
# uPassword.send_keys("Tal920420")
# driver.find_element(By.ID,"J-login").click()
#登陆方法2
#手机app扫码登录
driver.find_element(By.CLASS_NAME,"login-hd-account").click()

time.sleep(10)
#选择时间和始发和到达地
driver.find_element(By.ID,"J-index").click()
startDress = driver.find_element(By.ID,"fromStationText")
startDress.clear()
startDress.send_keys(start_address)#出发地
pyautogui.press('enter')
time.sleep(3)
endDress = driver.find_element(By.ID,"toStationText")
endDress.clear()
endDress.send_keys(end_address)#终止地
pyautogui.press('enter')
time.sleep(3)
trainDate = driver.find_element(By.ID,"train_date")
trainDate.clear()
trainDate.send_keys(start_time)#出发时间
pyautogui.press('enter')
trainType = driver.find_element(By.ID,"isHighDan")
#查询进入车程列表页
driver2=driver.find_element(By.ID,"search_one").click()


time.sleep(10)
goOn = True
while goOn:
    #获取当前时间
    now  = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    if now >= buy_time  :
        try:
            # 没有放票点击查询按钮刷新列表
            driver.find_element(by=By.CLASS_NAME, value="common-submit-btn").click()
        except:
            print('异常了')
            time.sleep(10)
    else:
        time.sleep(0.1)

    if now > buy_time :
        print("抢购已经结束！！！")
        try:
            driver.find_element(by=By.ID, value="order-submit").click()
        except:
            goOn = False
print("抢购结束了，没买到！")
driver.close()

